﻿using System;
using System.Threading;

namespace Networking.Runtime
{
    public static class DownLoadLoom
    {
        public static int maxThreads = 8;
        static int numThreads;
        
        public static void RunAsync(Action a)
        {
            while (numThreads >= maxThreads)
            {
                Thread.Sleep(100);
            }
            Interlocked.Increment(ref numThreads);
            ThreadPool.QueueUserWorkItem(RunAction, a);
        }

        private static void RunAction(object action)
        {
            try
            {
                ((Action) action)();
            }
            catch(Exception exception)
            {
                throw new ThreadStateException(exception.Message);
            }
            finally
            {
                Interlocked.Decrement(ref numThreads);
            }
        }
    }
}